﻿using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace JeanFish.Blog.Storage.Providers
{
    public class AzureBlobMediaProvider:BlogMediaProvider
    {
        private static bool storageInitialized = false;
        private static object gate = new object();
        private static CloudBlobClient blobStorage;
        private  void InitializeStorage()
        {
            if (storageInitialized)
            {
                return;
            }

            lock (gate)
            {
                if (storageInitialized)
                {
                    return;
                }

                try
                {
                    // read account configuration settings
                    var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("DataConnectionString"));

                    // create blob container for images
                    blobStorage = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container = blobStorage.GetContainerReference("blog");
                    container.CreateIfNotExists();

                    // configure container for public access
                    var permissions = container.GetPermissions();
                    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                    container.SetPermissions(permissions);
                }
                catch (WebException)
                {
                    throw new WebException("Storage services initialization failure. "
                       + "Check your storage account configuration settings. If running locally, "
                       + "ensure that the Development Storage service is running.");
                }

                storageInitialized = true;
            }
        }
        public async override Task<Uri> SaveMediaAsync(Storage.Blog blog, string mediaName, Stream mediaData)
        {
            this.InitializeStorage();

            // upload the image to blob storage
            string uniqueBlobName = string.Format("blog/{0}", mediaName);
           ICloudBlob blob = await blobStorage.GetBlobReferenceFromServerAsync(new Uri(uniqueBlobName));
            blob.Properties.ContentType = Path.GetExtension(mediaName);
            blob.UploadFromStream(mediaData);
            return blob.Uri;
        }

    }
}